package cjj.proxy.jdk;

import sun.misc.ProxyGenerator;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;

/**
 * @author chenjunjie
 * @since 2018-05-09
 */
public class MainTest {
    public static void main(String[] args) throws Exception {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "ture");

        // 方式一:
            MyInvocationHandler handler = new MyInvocationHandler(new HelloWorldImpl());
        ClassLoader loader = MainTest.class.getClassLoader();
        Class[] interfaces = new Class[]{HelloWorld.class};
        HelloWorld proxy = (HelloWorld) Proxy.newProxyInstance(loader, interfaces, handler);
        proxy.sayHello("cjj!");

        // 将生成的字节码保存到本地，
        createProxyClassFile();

        /*

        //方式二:
        System.out.println();
        Class proxyClazz = Proxy.getProxyClass(loader,interfaces);
        Constructor constructor = proxyClazz.getConstructor(InvocationHandler.class);
        HelloWorld proxy_hello = (HelloWorld) constructor.newInstance(handler);
        proxy_hello.sayHello("cjj");

        小记：
        方法一、方法二实际上都调用了Proxy中的getProxyClass0(loader,interfaces)方法来获取代理对象.
        */

        // 测试getInterfaces
        System.out.println();
        ClassLoader _loader_ = UserMapperImpl.class.getClassLoader();
        Class[] _interfaces_ = UserMapperImpl.class.getInterfaces();
        for(Class inf: _interfaces_){
            System.out.println(inf);
        }
    }

    private static void createProxyClassFile(){
        // 代理生成的class文件名称
        String name = "ProxySubject";
        byte[] data = ProxyGenerator.generateProxyClass(name,new Class[]{HelloWorld.class});
        FileOutputStream out =null;
        try {
            String path = MainTest.class.getResource("").getPath();
            String proxyFilePathName = path + name;
            out = new FileOutputStream(proxyFilePathName+".class");
            System.out.println("请到"+(new File(path)).getAbsolutePath()+"目录下查找生成的"+name+".class代理文件");
            out.write(data);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
